package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"week_one/user_srv/common/global"
)

func InitMysql(mysqlFunc func(DB *gorm.DB) error) error {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		global.ServerConfig.MysqlConf.Username, global.ServerConfig.MysqlConf.Password, global.ServerConfig.MysqlConf.Host, global.ServerConfig.MysqlConf.Port,
		global.ServerConfig.MysqlConf.Database,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}
	exit, _ := db.DB()
	defer exit.Close()
	return mysqlFunc(db)
}

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(18);not null;comment:账号" json:"Username"`
	Password string `gorm:"type:varchar(150);not null;comment:密码" json:"Password"`
	Salt     string `gorm:"type:varchar(100);not null;comment:盐值"`
	Status   int    `gorm:"type:tinyint(1);check:status IN (0,1);not null;comment:账号状态" json:"Status"`
}

func DatabaseMigrate() {
	err := InitMysql(func(DB *gorm.DB) error {
		return DB.AutoMigrate(&User{})
	})
	if err != nil {
		panic(err)
	}
}
